<%--
  Created by IntelliJ IDEA.
  User: lujiapeng
  Date: 2020/9/16
  Time: 14:41
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>

    <div id="name"></div>
    <div id="password"></div>
    <script type="text/javascript">
        // 1、初始化 XMLHttpRequest 对象
        let xhr = new XMLHttpRequest() ;
        // 当 创建实例完成之后，那么 readyState = 0 (请求未初始化)
        // 2、 打开与服务器的连接
        let method = "post" ;
        let url =  "${pageContext.request.contextPath}/ajax2" ;
        xhr.open( method , url  ) ;

        // 3、设置监听 XMLHttpRequest 状态改变的事件处理函数
        xhr.onreadystatechange = function(){
            if( xhr.readyState == XMLHttpRequest.DONE && xhr.status == 200 ){
                let x = JSON.parse( xhr.responseText ) ;
                console.log( x ) ;
                if( x.status == 0 ){
                    console.log( x.data ) ;
                        document.querySelector("#name").innerHTML = x.data.name;
                        document.querySelector("#password").innerHTML = x.data.password;
                }
            }
        }
        // 4、 设置请求报头
        xhr.setRequestHeader( "Content-Type" , "application/x-www-form-urlencoded");
        // 5、发送请求
        let data = "username=zhangsanfeng&password=123";

        // data = {username:"zhangsanfeng" , password:"123"} ;

        xhr.send( data ) ;
    </script>

</body>
</html>
